//
//  TelViewController.m
//  AipuTel
//
//  Created by cretve on 15/1/15.
//  Copyright (c) 2015年 aipu. All rights reserved.
//

#import "TelViewController.h"
#import "AppDelegate.h"
#import "ABWrappers.h"
#import <ADBIndexedTableView/ADBIndexedTableView.h>
#import "CallingViewController.h"

@interface TelViewController ()
{
    NSArray* _contacts;
    NSMutableArray* _searchResults;
}

@property (weak, nonatomic) IBOutlet ADBIndexedTableView *tableView;

@end

@implementation TelViewController

- (void)awakeFromNib
{
    self.tabBarItem.title = @"通讯录";
    self.tabBarItem.image = [[UIImage imageNamed:@"tel"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tel"] imageWithWhiteMask];
    
    _searchResults = [NSMutableArray array];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"点话通";
    
    _contacts = ((AppDelegate*)[UIApplication sharedApplication].delegate).contacts;
    [_tableView reloadDataWithObjects:_contacts];
}

#pragma mark -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == _tableView)
    {
        ADBMessageInterceptor* interceptor = tableView.dataSource;
        return [interceptor.secondChance tableView:tableView numberOfRowsInSection:section];
    }
    else
        return _searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == _tableView)
    {
        ADBMessageInterceptor* interceptor = tableView.dataSource;
        return [interceptor.secondChance tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    else
    {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
        }
        
        ABContact* contact = _searchResults[indexPath.row];
        cell.textLabel.text = contact.displayName;
        cell.detailTextLabel.text = contact.phoneArray.firstObject;
        
        return cell;
    }
}

- (NSString *)objectsFieldForIndexedTableView:(ADBIndexedTableView *)tableView
{
    return @"displayName";
}

- (UITableViewCell *)indexedTableView:(ADBIndexedTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath usingObject:(id)object
{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    ABContact* contact = (ABContact*)object;
    cell.textLabel.text = contact.displayName;
    cell.detailTextLabel.text = contact.phoneArray.firstObject;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary* userInfo = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"UsreInfo"];
    if(userInfo.count == 0)
    {
        [UIAlertView bk_showAlertViewWithTitle:@"请先登录" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
        return;
    }
    
    ABContact* contact;
    if(tableView == _tableView)
        contact = [_tableView objectAtIndexPath:indexPath];
    else
        contact = _searchResults[indexPath.row];
    
    NSString* number = contact.phoneArray.firstObject;
    if([number hasPrefix:@"+"])
    {
        if([number hasPrefix:@"+86"])
            number = [number substringFromIndex:3];
        else
        {
            [UIAlertView bk_showAlertViewWithTitle:@"只能拨打国内电话" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
            return;
        }
    }
    
    number = [[number componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
    
    if([number hasPrefix:@"1"] || [number hasPrefix:@"0"])
    {
        if(number.length != 11)
        {
            [UIAlertView bk_showAlertViewWithTitle:@"该电话号码不正确" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
            return;
        }
    }
    else if(number.length < 7 || number.length > 8)
    {
        [UIAlertView bk_showAlertViewWithTitle:@"该电话号码不正确" message:nil cancelButtonTitle:@"好" otherButtonTitles:nil handler:nil];
        return;
    }
    
    NSMutableArray* historyArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:@"CallHistory"]];
    [historyArray insertObject:@{@"phone": number, @"date": [NSDate date]} atIndex:0];
    
    [[NSUserDefaults standardUserDefaults] setObject:historyArray forKey:@"CallHistory"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    CallingViewController* cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"CallingViewController"];
    cvc.number = number;
    
    [self presentViewController:cvc animated:YES completion:nil];
}

#pragma mark -

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [_searchResults removeAllObjects];
    
    for(ABContact* contact in _contacts)
    {
        if([contact.compositeName.uppercaseString rangeOfString:searchString.uppercaseString].location != NSNotFound)
            [_searchResults addObject:contact];
        else
        {
            NSString* number = [[contact.phoneArray.firstObject componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
            if([number rangeOfString:searchString].location != NSNotFound)
                [_searchResults addObject:contact];
        }
    }
    
    return YES;
}

@end
